package com.oocl.chatroom.server.listener;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.Map;

import com.oocl.chatroom.server.infohandle.MsgParse;
import com.oocl.chatroom.server.infohandle.MsgParseImpl;
import com.oocl.chatroom.network.protocol.Message;
import com.oocl.chatroom.server.ChatServer;
import com.oocl.chatroom.server.OnlineSocket;
import com.oocl.chatroom.server.sender.Sender;

public class MessageListener implements Runnable{
     private OnlineSocket onlineSocket;
     private Map<String,OnlineSocket> users;
     private ChatServer server;
     
     public void setServer(ChatServer server) {
    	 this.server = server;
     }
     
     public MessageListener(Socket socket){
    	 
    	 this.onlineSocket = new OnlineSocket(socket);
     }
     
     



	public void run() {
		while(onlineSocket.getSocket().isConnected()){
			try {
				boolean status = solveMessage();
				if(!status) break;
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				if(e instanceof IOException){
					users.remove(onlineSocket.getName());
					users.put(onlineSocket.getName(), null);
					Message downlineMsg = new Message(onlineSocket.getName()+" is down line",3,"server",onlineSocket.getName(),System.currentTimeMillis()); 
					MsgParseImpl  msgParse = new MsgParseImpl(onlineSocket,users);
					  try {
						msgParse.nodifyDownlineMsg(downlineMsg);
					} catch (IOException e1) {
						
					}
					  break;
				}
			} 
		}
	}

	private boolean solveMessage() throws ClassNotFoundException, IOException {
	  MsgParse  msgParse = new MsgParseImpl(onlineSocket,users);
	  msgParse.setServer(server);
	  return msgParse.solveMessage();
	}

	public OnlineSocket getOnlineSocket() {
		return onlineSocket;
	}

	public void setOnlineSocket(OnlineSocket onlineSocket) {
		this.onlineSocket = onlineSocket;
	}

	public Map<String, OnlineSocket> getUsers() {
		return users;
	}

	public void setUsers(Map<String, OnlineSocket> users) {
		this.users = users;
	}


	
}
